@using System.Globalization;
@using OrchardCore.ContentManagement.Metadata.Settings;
@model OrchardCore.Layers.ViewModels.LayersIndexViewModel

@inject IContentManager ContentManager
@inject OrchardCore.ContentManagement.Metadata.IContentDefinitionManager ContentDefinitionManager
@inject OrchardCore.ContentManagement.Display.IContentItemDisplayManager ContentItemDisplayManager

@{
    var widgetContentTypes = ContentDefinitionManager.ListTypeDefinitions().Where(t => t.Settings.ToObject<ContentTypeSettings>().Stereotype == "Widget");
}
<script asp-name="jquery-ui" at="Foot"></script>

<h1>@RenderTitleSegments(T["Edit Widget Layers"])</h1>

<form id="undo-form" asp-action="UpdatePosition" method="post">
    <div id="layer-undo-message" class="alert alert-success alert-dismissible show d-none" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        @T["Widget successfully moved. <a href=\"javascript:console.log('submit');$('#undo-form').submit();\"><strong>Undo</strong></a>."]
    </div>
    <input id="layer-undo-message-contentItemId" type="hidden" name="contentItemId" value="" />
    <input id="layer-undo-message-zone" type="hidden" name="zone" value="" />
    <input id="layer-undo-message-position" type="hidden" name="position" value="" />
</form>

<div class="row">
    <div class="col-md-8">
        <h3>@T["Zones"]</h3>
        <form asp-action="Index">
            @foreach (var zone in Model.Zones)
            {
                double maxPosition = 0;

                <div class="card form-group">
                    <div class="card-header text-muted">
                        @zone
                    </div>
                    <div class="layer-zone card-body" data-zone="@zone">
                        <div class="form-group">
                            <ul class="list-group">
                                @if (Model.Widgets.ContainsKey(zone))
                                {
                                    foreach (var contentItemSummary in Model.Widgets[zone])
                                    {
                                        contentItemSummary.Meta.Add(Html.Raw("<span class=\"badge badge-info\"><i class=\"fa fa-bookmark-o\" aria-hidden=\"true\"></i> " + contentItemSummary.ContentItem.Content.LayerMetadata.Layer + "</span>"));

                                        maxPosition = Math.Max(maxPosition, (double)contentItemSummary.ContentItem.Content.LayerMetadata.Position);
                                        <li class="list-group-item">
                                            @await DisplayAsync(contentItemSummary)
                                            <input type="hidden"
                                                   class="layer-metadata"
                                                   data-zone="@zone"
                                                   data-layer="@contentItemSummary.ContentItem.Content.LayerMetadata.Layer"
                                                   data-position="@contentItemSummary.ContentItem.Content.LayerMetadata.Position.ToString(CultureInfo.InvariantCulture)"
                                                   data-content-item-id="@contentItemSummary.ContentItem.ContentItemId" />
                                        </li>
                                    }
                                }
                            </ul>
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                @T["Add Widget"]
                            </button>
                            <div class="dropdown-menu">
                                @foreach (var type in widgetContentTypes)
                                {
                                    var contentItem = await ContentManager.NewAsync(type.Name);
                                    var createRoute = (await ContentManager.PopulateAspectAsync<ContentItemMetadata>(contentItem)).CreateRouteValues;
                                    createRoute["returnUrl"] = Context.Request.PathBase + Context.Request.Path;
                                    createRoute["LayerMetadata.Zone"] = zone;
                                    createRoute["LayerMetadata.Position"] = maxPosition + 1;
                                    <a class="dropdown-item add-list-widget btn-sm"
                                       data-widget-type="@type.Name"
                                       data-zone="@zone"
                                       href="@Url.Action((string)createRoute["Action"], (string)createRoute["controller"], createRoute)">@type.DisplayName</a>
                                }
                            </div>
                        </div>
                    </div>
                </div>
            }
        </form>
    </div>
    <div class="col-md-4 col-md-pull-right">
        <h3>@T["Layers"]</h3>
        <p>
            <span class="hint">@T["Select a layer to reveal its associated widgets."]</span>
        </p>
        <div class="form-group">
            <ul class="list-group">
                @foreach (var layer in Model.Layers)
                {
                    <li class="list-group-item">
                        <div class="properties">
                            <div class="d-flex flex-wrap">
                                <div class="custom-control custom-checkbox mr-auto flex-grow-1">
                                    <input type="checkbox" class="custom-control-input layer-check" id="@layer.Name" value="@layer.Name">
                                    <label class="custom-control-label" for="@layer.Name">@layer.Name</label>
                                </div>
                                <div>
                                    <a class="btn btn-primary btn-sm" href="@Url.Action("Edit", "Admin", new { area = "OrchardCore.Layers", name = layer.Name })">@T["Edit"]</a>
                                    <a class="btn btn-danger btn-sm" href="@Url.Action("Delete", "Admin", new { area = "OrchardCore.Layers", name = layer.Name })" itemprop="RemoveUrl UnsafeUrl">@T["Delete"]</a>
                                </div>
                            </div>
                            <div>
                                <span class="hint">@layer.Description</span>
                            </div>
                        </div>
                    </li>
                }
            </ul>
        </div>
        @if (!Model.Layers.Any())
        {
            <p class="alert alert-warning">@T["Please <a href=\"{0}\">create a layer</a> before adding Widgets", Url.Action("Create", "Admin", new { area = "OrchardCore.Layers" })]</p>
        }

        <a class="button btn-sm" href="@Url.Action("Create", "Admin", new { area = "OrchardCore.Layers" })">@T["Add"]</a>
    </div>
</div>

<script at="Foot">
    $(".list-group").sortable({
        handle: ".properties",
        cursor: "move",
        connectWith: '.list-group',
        stop: function (event, ui) {
            var newZone = ui.item.closest('.layer-zone').data("zone");
            var metadata = ui.item.find('.layer-metadata')
            var currentPosition = Number(metadata.data("position"));
            var item = ui.item.closest('.list-group-item');
            var previous = item.prev('.list-group-item').find('.layer-metadata');
            var next = item.next('.list-group-item').find('.layer-metadata');
            var contentItemId = metadata.data("content-item-id");

            var newPosition = currentPosition;

            if (previous.length == 0 && next.length == 0) {
                // we can keep the current position
            }
            else if (previous.length == 0 && next.length > 0) {
                // first in the list
                newPosition = Number(next.data("position") || 0) - 1;
            }
            else if (previous.length > 0 && next.length == 0) {
                // last in the list
                newPosition = Number(previous.data("position") || 0) + 1;
            }
            else {
                newPosition = (Number(previous.data("position") || 0) + Number(next.data("position") || 0)) / 2;
            }

            var currentZone = metadata.data("zone");
            var currentPosition = metadata.data("position");

            metadata.data("zone", newZone);
            metadata.data("position", newPosition);

            var url = "@Url.Action("UpdatePosition", "Admin", new { area = "OrchardCore.Layers" })" + "?" + "contentItemId=" + encodeURIComponent(contentItemId) + "&position=" + encodeURIComponent(newPosition) + "&zone=" + encodeURIComponent(newZone);
            var antiforgerytoken = $("[name='__RequestVerificationToken']").val();

            $.post(url, { "__RequestVerificationToken": antiforgerytoken })
                .done(function () {
                    console.log('done');
                    $('#layer-undo-message').removeClass("d-none");
                    $('#layer-undo-message-contentItemId').val(contentItemId);
                    $('#layer-undo-message-position').val(currentPosition);
                    $('#layer-undo-message-zone').val(currentZone);
                })
                .fail(function () {
                    console.log('failed');
                    $('#layer-undo-message').addClass("d-none");
                })
            ;
        }
    });

    $('.layer-check').on('click', function () {
        $('.list-group-item').removeClass('list-group-item-success');
        $('.layer-check:checked').each(function () {
            var layer = $(this).val();
            $('[data-layer="' + layer + '"]').closest('.list-group-item').addClass('list-group-item-success');
        });
    });
</script>